package com.zjdiepu.www.biz.cw;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.dao.cw.CwIncomeExpensesItemMapper;
import com.zjdiepu.www.dao.cw.CwIncomeExpensesMapper;
import com.zjdiepu.www.dao.yw.YwBusinessMapper;
import com.zjdiepu.www.ibiz.cw.ICwIncomeExpensesService;
import com.zjdiepu.www.model.cw.dto.CwIncomeExpenses;
import com.zjdiepu.www.model.cw.dto.CwIncomeExpensesItem;
import com.zjdiepu.www.model.cw.ext.CwIncomeExpensesExt;
import com.zjdiepu.www.model.cw.ext.CwIncomeExpensesItemExt;
import com.zjdiepu.www.model.cw.request.IncomeExpensesSaveRequest;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.util.ExceptionHelper;

/**
 * 收支管理Service层操作实现<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年05月15日 18时13分<br/>
 * @since 1.0<br/>
 */
@Service
public class CwIncomeExpensesServiceImpl extends BaseService implements ICwIncomeExpensesService {
	public static final Logger logger = LoggerFactory.getLogger(CwIncomeExpensesServiceImpl.class);

	@Autowired
	private YwBusinessMapper ywBusinessMapper;
	@Autowired
	private CwIncomeExpensesMapper cwIncomeExpensesMapper;
	@Autowired
	private CwIncomeExpensesItemMapper cwIncomeExpensesItemMapper;
	
	@Override
	public ApiResponse saveCommit(String busiId, String id, AbstractSysUser currentUser) {
		CwIncomeExpenses cwIncomeExpenses = cwIncomeExpensesMapper.selectByPrimaryKey(id);
		if(null == cwIncomeExpenses.getDateComplete()) {
			ExceptionHelper.thow("999","应收款齐全时间不能为空");
		}
		YwBusiness ywBusiness = new YwBusiness();
		ywBusiness.setId(busiId);
		ywBusiness.setDateComplete(cwIncomeExpenses.getDateComplete());
		ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness);
		return ApiResponse.success(true);
	}
	@Override
	public ApiResponse saveIncomeExpenses(
			IncomeExpensesSaveRequest incomeExpensesSaveRequest,
			AbstractSysUser currentUser) {
		CwIncomeExpenses cwIncomeExpenses = new CwIncomeExpenses();
		cwIncomeExpenses.setBusiId(incomeExpensesSaveRequest.getBusiId());
		cwIncomeExpenses.setCusId(incomeExpensesSaveRequest.getCusId());
		cwIncomeExpenses.setDateComplete(incomeExpensesSaveRequest.getDateComplete());
		cwIncomeExpenses.setRemarks(incomeExpensesSaveRequest.getRemarks());
		String id = incomeExpensesSaveRequest.getId();
		if(StringUtils.isNotBlank(id)) {
			cwIncomeExpenses.initUpdateData(currentUser.getId(), currentUser.getName());
			cwIncomeExpenses.setId(id);
			cwIncomeExpensesMapper.updateByPrimaryKeySelective(cwIncomeExpenses);
		} else {
			cwIncomeExpenses.initInsertData(currentUser.getId(), currentUser.getName());
			cwIncomeExpensesMapper.insert(cwIncomeExpenses);
		}
		CwIncomeExpensesItemExt cwIncomeExpensesItemExt = new CwIncomeExpensesItemExt();
		cwIncomeExpensesItemExt.setBaseWhere();
		cwIncomeExpensesItemExt.withOutPage();
		cwIncomeExpensesItemExt.setBusiId(incomeExpensesSaveRequest.getBusiId());
		List<CwIncomeExpensesItem> cwIncomeExpensesItems_ = cwIncomeExpensesItemMapper.selectByExt(cwIncomeExpensesItemExt);
		List<String> itemIds = cwIncomeExpensesItems_.stream().map(item -> item.getId()).collect(Collectors.toList());
		
		List<Map<String,String>> details = incomeExpensesSaveRequest.getDetails();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if(CollectionUtils.isNotEmpty(details)){
			List<CwIncomeExpensesItem> cwIncomeExpensesItems = new ArrayList<CwIncomeExpensesItem>();
			for(Map<String,String> detail : details) {
				String itemId = (String)detail.get("replaceId");
				if(!itemId.startsWith("replaceId")){
					itemIds.remove(itemId);
					continue;
				}
				
				CwIncomeExpensesItem cwIncomeExpensesItem = new CwIncomeExpensesItem();
				cwIncomeExpensesItem.initInsertData(currentUser.getId(), currentUser.getName());
				itemId = itemId.substring("replaceId".length());
				cwIncomeExpensesItem.setId(itemId);
				cwIncomeExpensesItem.setBusiId(incomeExpensesSaveRequest.getBusiId());
				cwIncomeExpensesItem.setCusId(incomeExpensesSaveRequest.getCusId());
				cwIncomeExpensesItem.setParentId(cwIncomeExpenses.getId());
				String amountItem = detail.get("amountItem");
				cwIncomeExpensesItem.setAmountItem(Double.parseDouble(StringUtils.isNotBlank(amountItem) ? amountItem : "0"));
				cwIncomeExpensesItem.setBankItem(detail.get("bankItem"));
				cwIncomeExpensesItem.setCardnoItem(detail.get("cardnoItem"));
				cwIncomeExpensesItem.setRemarks(detail.get("remarks"));
				cwIncomeExpensesItem.setTypeRemit(detail.get("typeRemit"));
				cwIncomeExpensesItem.setItemDirection(detail.get("itemDirection"));
				cwIncomeExpensesItem.setItemCode(detail.get("itemCode"));
				try {
					String dateItem = detail.get("dateItem");
					cwIncomeExpensesItem.setDateItem(StringUtils.isBlank(dateItem) ? null : sdf.parse(dateItem));
				} catch (ParseException e) {
					logger.debug("时间格式转换出错.", e);
				}
				cwIncomeExpensesItems.add(cwIncomeExpensesItem);
			}
			if(CollectionUtils.isNotEmpty(cwIncomeExpensesItems)){
				cwIncomeExpensesItemMapper.insertBatch(cwIncomeExpensesItems);
			}
		}
		
		if(CollectionUtils.isNotEmpty(itemIds)) {
			cwIncomeExpensesItemMapper.updateBatch(currentUser.getId(), currentUser.getName(), (int)(System.currentTimeMillis() / 1000), DpStatus.DELETED.getCode(), itemIds);
		}
		
		return ApiResponse.success(cwIncomeExpenses.getId());
	}
	
	@Override
	public void saveUpdateAndDelete(CwIncomeExpenses cwIncomeExpenses, OperateType operType) {
		switch (operType) {
		case add:
			cwIncomeExpenses.initInsertData(cwIncomeExpenses.getModifier(), cwIncomeExpenses.getModifierName());
			cwIncomeExpensesMapper.insert(cwIncomeExpenses);
			break;
		case edit:
			cwIncomeExpenses.initUpdateData(cwIncomeExpenses.getModifier(), cwIncomeExpenses.getModifierName());
			// 影响的记录数
			int updateCount = cwIncomeExpensesMapper.updateByPrimaryKeySelective(cwIncomeExpenses);
			if(updateCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(updateCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		case delete:
			cwIncomeExpenses.initDeleteData(cwIncomeExpenses.getModifier(), cwIncomeExpenses.getModifierName());
			// 影响的记录数
			int deleteCount = cwIncomeExpensesMapper.updateByPrimaryKeySelective(cwIncomeExpenses);
			if(deleteCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(deleteCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		default:
			break;
		}
	}
	
	@Override
	public List<CwIncomeExpenses> selectByExt(CwIncomeExpensesExt cwIncomeExpensesExt) {
		return cwIncomeExpensesMapper.selectByExt(cwIncomeExpensesExt);
	}
	
	@Override
	public int countByExt(CwIncomeExpensesExt cwIncomeExpensesExt){
		return cwIncomeExpensesMapper.countByExt(cwIncomeExpensesExt);
	}
	
	@Override
	public CwIncomeExpenses selectById(String id) {
		return cwIncomeExpensesMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public void clearEmpty(Set<String> fieldNames, String id) {
		if(CollectionUtils.isNotEmpty(fieldNames)){
			cwIncomeExpensesMapper.clearEmpty(fieldNames, id);
		}
	}
	
	@Override
	public int countRefined(CwIncomeExpenses cwIncomeExpenses) {
		return cwIncomeExpensesMapper.countRefined(cwIncomeExpenses);
	}

	@Override
	public CwIncomeExpenses selectRefined(CwIncomeExpenses cwIncomeExpenses) {
		return cwIncomeExpensesMapper.selectRefined(cwIncomeExpenses);
	}
	
	@Override
	public int deletedRefined(CwIncomeExpenses cwIncomeExpenses) {
		return cwIncomeExpensesMapper.deletedRefined(cwIncomeExpenses);
	}

	@Override
	public boolean repeat(CwIncomeExpenses cwIncomeExpenses) {
		int count = countRefined(cwIncomeExpenses);
		if(count > 1) {
			return true;
		}
		if(count == 0) {
			return false;
		}
		
		if(StringUtils.isBlank(cwIncomeExpenses.getId())) {
			return true;
		}
		CwIncomeExpenses dbItem = selectRefined(cwIncomeExpenses);
		if(null == dbItem) {
			return false;
		}
		return !cwIncomeExpenses.getId().equals(dbItem.getId());
	}
	
	@Override
	public int updateBatch(String modifier, String modifierName, Integer dpStatus, List<String> ids) {
		Integer current = (int)(System.currentTimeMillis() / 1000);
		return cwIncomeExpensesMapper.updateBatch(modifier, modifierName, current, dpStatus, ids);
	}
	
	@Override
	public int insertBatch(List<CwIncomeExpenses> cwIncomeExpensess) {
		return cwIncomeExpensesMapper.insertBatch(cwIncomeExpensess);
	}
}
